package com.nami.ucenter.controller.midddleware.mq.consumer;

import com.google.protobuf.InvalidProtocolBufferException;
import com.nami.gate.external.basic.constants.UpTopicConst;
import com.nami.transport.proto.codec.MqTransMsg;
import com.nami.transport.proto.codec.UpWsMsg;
import com.nami.ucenter.controller.convertor.WrapToLoginCmdAssembler;
import com.nami.transport.utils.MsgTimeUtil;
import com.nami.ucenter.facade.login.ConnectLoginFacade;
import com.nami.ucenter.facade.login.request.command.UserLoginCmd;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@AllArgsConstructor
@RocketMQMessageListener(topic = UpTopicConst.LOGIN_TOPIC,
    consumerGroup = UpTopicConst.LOGIN_CONSUMER_GROUP,
    consumeMode = ConsumeMode.CONCURRENTLY)
public class LoginConsumer implements RocketMQListener<MessageExt> {

    private final ConnectLoginFacade loginFacade;

    @Override
    public void onMessage(MessageExt message) {
        try {
            UserLoginCmd command = parseLoginMessage(message.getBody());
            // 3. 检查消息时效性
            if (command == null || MsgTimeUtil.isMessageExpired(command.getCurrTime())) {
                log.warn("[login] 消息过期，不予处理.  mq消息消费成功！userId={}", command.getUserId());
                return;
            }
            loginFacade.execute(command);
        } catch (Exception var3) {
            var3.printStackTrace();
            log.error("[login] 登录逻辑出现错误 msg=", var3);
        }
    }

    private UserLoginCmd parseLoginMessage(byte[] message) {
        MqTransMsg.Gate2LogicLoginRequest loginMsgBody = null;
        UpWsMsg.ConnectMsgBody connectMsgBody = null;
        try {
            loginMsgBody = MqTransMsg.Gate2LogicLoginRequest.parseFrom(message);
            connectMsgBody = UpWsMsg.ConnectMsgBody.parseFrom(loginMsgBody.getMsg());
        } catch (InvalidProtocolBufferException var2) {
            var2.printStackTrace();
            throw new RuntimeException(var2);
        }
        return WrapToLoginCmdAssembler.toUserLoginCommand(loginMsgBody, connectMsgBody);
    }

}
